package org.rcgwt.client.ui.grid.internal;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.HasHandlers;
import com.google.gwt.event.shared.GwtEvent.Type;

/**
 * 
 * @author Olivier Oeuillot (latest modification by $Author: $)
 * @version $Revision: $ $Date: $
 */
public abstract class HandlerManagerProvider implements HasHandlers {

    private HandlerManager handlerManager;

    protected HandlerManager ensureHandlers() {
        return handlerManager == null ? handlerManager = new HandlerManager(
                this) : handlerManager;
    }

    /**
     * Adds this handler to the Model.
     * 
     * @param <H>
     *            the type of handler to add
     * @param type
     *            the event type
     * @param handler
     *            the handler
     * @return {@link HandlerRegistration} used to remove the handler
     */
    protected final <H extends EventHandler> HandlerRegistration addHandler(
            final H handler, GwtEvent.Type<H> type) {
        return ensureHandlers().addHandler(type, handler);
    }

    @Override
    public void fireEvent(GwtEvent< ? > event) {
        if (handlerManager != null) {
            handlerManager.fireEvent(event);
        }
    }

    /**
     * Gets the number of handlers listening to the event type.
     * 
     * @param type
     *            the event type
     * @return the number of registered handlers
     */
    protected int getHandlerCount(Type< ? > type) {
        return handlerManager == null ? 0 : handlerManager
                .getHandlerCount(type);
    }

}
